<script setup lang="ts">
// 编辑视频弹窗
import { computed, nextTick, reactive, ref, watch } from 'vue';
import mammoth from 'mammoth';
import _ from 'underscore';
import * as htmlDocx from 'html-docx-js-typescript';
import { saveAs } from 'file-saver';
import { getLogCatalogAction } from '@/service/api';
import {
  convertImageToBase64,
  errorMessage,
  escapeHTMLManually,
  generateRandomCode,
  getImageInfoFromBase64,
  successMessage
} from '@/utils/utils';

interface Props {
  show: boolean;
  taskId?: number;
  title?: any;
  formatObj?: any;
  catalogNum?: number;
}

const props = withDefaults(defineProps<Props>(), {
  show: false
});

const showLoading = ref<boolean>(true);
const loadingDes = ref<string>('文档较大，正在努力处理中，请稍后...');
const isBack = ref<boolean>(false);
const fileList = ref<any[]>([]);

const docContentHtml = ref<string>('');
const contentHtml = ref<string>('');
const imgList = ref<any[]>([]);
const IMAGE_TAG: string = 'IMAGE_TAG';
const catalogMap: any = {};

const firstNum = ref<number>(0);
const secondNum = ref<number>(0);
const thirdNum = ref<number>(0);
const fourthNum = ref<number>(0);
const fifthNum = ref<number>(0);
const sixthNum = ref<number>(0);

// 编辑器配置
const editorConfig: object = reactive({
  serverUrl: '',
  UEDITOR_HOME_URL: '/modules/bidWriting/UEditorPlus/',
  UEDITOR_CORS_URL: '/modules/bidWriting/UEditorPlus/',
  toolbars: [],
  readonly: true,
  autoFloatEnabled: false,
  autoSaveEnable: false, // 禁用自动保存
  elementPathEnabled: false, // 禁用元素路径
  initialFrameHeight: '620',
  autoHeightEnabled: false, // 禁止编辑器自动长高
  maximumWords: 2000000
});

// 引入的js文件，这里是一定要写的。
const editorDependencies: string[] = reactive(['ueditor.config.js', 'ueditor.all.js', 'lang/zh-cn/zh-cn.js']);

const ueditor = ref<any | null>(null);

function readyHandle(editor: any) {
  ueditor.value = editor;

  // 监听内容变化
  ueditor.value.addListener('updateSections', getCatalogHandle);

  getLogCatalogData();
}

watch(
  () => props.show,
  value => {
    if (value) {
      isBack.value = false;
      contentHtml.value = '';
      docContentHtml.value = '';
      fileList.value = [];

      firstNum.value = 0;
      secondNum.value = 0;
      thirdNum.value = 0;
      fourthNum.value = 0;
      fifthNum.value = 0;
      sixthNum.value = 0;

      if (ueditor.value) {
        getLogCatalogData();
      }
    }
  }
);

// 获取文档目录树
function getCatalogHandle() {
  const catalogTree: any = ueditor.value.execCommand('getsections');

  const directoryTree = analyzeDirectoryTree(catalogTree);

  if (!directoryTree) return;

  // 更新目录树
  const catalogEle = document.getElementById('catalog_box')!;
  catalogEle.innerHTML = directoryTree?.outerHTML;

  /** 选中章节监听sectionItem的点击事件会让下面其他点击事件优先跳转到对应内容再触发 监听itemTitle的点击事件只会点击章节标题才会跳转 */
  // 选中章节
  const sectionItemEle = document.getElementsByClassName('itemTitle');
  for (let i: number = 0; i < sectionItemEle.length; i++) {
    sectionItemEle[i].addEventListener('click', (e: any) => {
      console.log('e: ', e, e.target);
      const address = e.target.parentElement.getAttribute('data-address');
      ueditor.value.execCommand('selectsection', catalogMap[address], true);
      // 清除选区
      ueditor.value.selection.clearRange();
    });
  }
}

// 解析目录树
function analyzeDirectoryTree(section: any) {
  let liItem;
  let sectionItem;
  let itemContent;
  let ulList;
  let child;
  let childList;
  if (section.children.length) {
    ulList = document.createElement('ul');
    for (let i: number = 0; i < section.children.length; i++) {
      child = section.children[i];
      // console.log("child.startAddress: ", child)
      // 设置目录节点内容标签
      const title = child.title;
      if (title.length === 0) return null;

      // 目录标题
      sectionItem = document.createElement('span');
      sectionItem.className = 'itemTitle';
      sectionItem.textContent = title;

      itemContent = document.createElement('div');
      itemContent.className = 'sectionItem';
      itemContent.append(sectionItem);
      itemContent.setAttribute('data-address', child.startAddress.join(','));

      catalogMap[child.startAddress.join(',')] = child;
      // 设置目录节点容器标签
      liItem = document.createElement('li');
      liItem.setAttribute('type', child.tag);
      liItem.append(itemContent);
      // 继续遍历子节点
      if (liItem.children.length) {
        childList = analyzeDirectoryTree(child);
        childList && liItem.append(childList);
      }
      ulList.append(liItem);
    }
  }
  return ulList;
}

// 根据文档获取html内容
function getHtmlByDocument(item: any, filePath: string) {
  const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
  const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);
  const docPath: string = otherUrl.fileUrl + filePath;

  // loadingDes.value = '文档较大，正在努力处理中，请稍后...';
  // showLoading.value = true;
  return new Promise((resolve, reject) => {
    if (!filePath) {
      docContentHtml.value = item.title;

      // 插入文本
      ueditor.value.setContent(docContentHtml.value, true);
      // 设置内容光标到内容最前面
      ueditor.value.focus();
      getCatalogHandle();
      resolve(docContentHtml.value);
      return;
    }
    fetch(docPath, { cache: 'no-cache' })
      .then(response => response.blob())
      .then(async blobData => {
        let file: File | null = new File([blobData], `${props.title}.docx`, {
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          lastModified: Date.now()
        });

        analysisWord(file).then(html => {
          docContentHtml.value = item.title + docContentHtml.value;

          for (let i: number = 0; i < imgList.value.length; i++) {
            docContentHtml.value = docContentHtml.value.replace(IMAGE_TAG, imgList.value[i]);
          }
          docContentHtml.value = docContentHtml.value.replace(/style=""/g, "");
          // 插入文本
          ueditor.value.setContent(docContentHtml.value, true);
          // 设置内容光标到内容最前面
          ueditor.value.focus();
          getCatalogHandle();
          resolve(docContentHtml.value);
          // showLoading.value = false;
        });

        // 文件信息置空
        file = null;
        // showLoading.value = false;
      })
      .catch(error => {
        console.error('发生错误：', error);
        errorMessage('获取文档失败');
        // showLoading.value = false;
      });
  });
}

// 解析word文件，将word转为html
function analysisWord(file: any) {
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.onload = evt => {
      // console.log('evt：', evt);
      // 当文件读取完毕后
      // p标签首行没有缩进
      const options = {
        transformDocument: transformElement,
        styleMap: ["p[style-name='Section Title'] => h1:fresh", "p[style-name='Subsection Title'] => h2:fresh"]
      };

      // 调用mammoth组件的方法进行解析文件
      mammoth
        .convertToHtml({ arrayBuffer: evt.target!.result }, options)
        .then(async resultObject => {
          // console.log("resultObject: ", resultObject);
          // resultObject.value = imgTagAddStyle(resultObject.value);
          const imgSrcReg = /<img[^>]+src=[\\'|\\"]?([^(?"|?'|?>)]+)[\\'|\\"]?[^>]*>/gim;
          const imgSrcList = resultObject.value.match(imgSrcReg);

          for (let i: number = 0; i < imgSrcList?.length; i++) {
            const imgSrc: string = imgSrcList[i].match(/src="(.+?)"/)[1];

            // console.log('imgSrc: ', imgSrc);
            const info = await getImageInfoFromBase64(imgSrc);
            if (info) {
              imgSrcList[i] =
                `${imgSrcList[i].substring(0, imgSrcList[i].length - 2)}width="${info.width}" height="${info.height}" ${imgSrcList[i].substring(imgSrcList[i].length - 2)}`;
            } else {
              imgSrcList[i] =
                `${imgSrcList[i].substring(0, imgSrcList[i].length - 2)}width="90%" height="auto" ${imgSrcList[i].substring(imgSrcList[i].length - 2)}`;
            }

            // 使用DOM解析器创建一个DOM元素
            // const domParser = new DOMParser();
            // const contentDom = domParser.parseFromString(imgSrcList[i], 'text/html');
            // const imgNode = contentDom.body.childNodes;
            //
            // console.log('imgNode: ', imgNode);
          }

          if (imgSrcList) {
            imgList.value = imgSrcList;
          }

          resolve(resultObject.value); // 将处理好的html数据返回
          reader.abort(); // 关闭读取
        })
        .catch(err => {
          console.log('err: ', err);
          reader.abort(); // 关闭读取
        });
    };
    reader.readAsArrayBuffer(file);
    // 启动读取指定的 Blob 或 File 内容：https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsArrayBuffer
  });
}

// 元素重新定义
function transformElement(element: any) {
  if (element.children) {
    const children: any = _.map(element.children, transformElement);
    element = { ...element, children };
  }

  if (element.type === 'paragraph') {
    element = transformParagraph(element);
  }

  if (element.type === 'document') {
    // docParagraphList.value = element.children;
    // console.log('docParagraphList.value: ', element.children);
    htmlFormat(element.children);
  }

  return element;
}

// 段落内容重新定义
function transformParagraph(element: any) {
  if (element.alignment === 'center' && !element.styleId) {
    return { ...element, styleId: 'Heading2' };
  }
  return element;
}

// 根据文档解析API进行HTML内容拼接封装
function htmlFormat(docParagraphList: any[]) {
  let docHtmlStr: string = '';
  for (let i: number = 0; i < docParagraphList.length; i++) {
    const paragraphObj: any = docParagraphList[i];
    if (paragraphObj.type === 'paragraph') {
      // 普通段落内容（包括文字和图片）
      let paragraphStr: string = '';
      let alignmentStr: string = '';
      if (paragraphObj.alignment) {
        alignmentStr = `text-align: ${paragraphObj.alignment}; line-height: 150%; align-items: baseline;`;
      } else {
        alignmentStr = 'text-align: left; line-height: 150%; align-items: baseline;';
      }

      for (let j: number = 0; j < paragraphObj.children.length; j++) {
        if (paragraphObj.children.length > 1 && j === 0 && paragraphObj.indent.firstLine) {
          alignmentStr = 'text-indent: 2em;';
        }
        const formatContent = paragraphHtmlFormat(paragraphObj.children[j]);
        if (formatContent === IMAGE_TAG) {
          alignmentStr = 'display: block;text-align: center;';
        }
        paragraphStr += formatContent;
      }
      if (paragraphObj.styleId === 'Heading1' || paragraphObj.styleName === 'heading 1') {
        docHtmlStr += `<h1 style="${alignmentStr}">${paragraphStr}</h1>`;
      } else if (paragraphObj.styleId === 'Heading2' || paragraphObj.styleName === 'heading 2') {
        docHtmlStr += `<h2 style="${alignmentStr}">${paragraphStr}</h2>`;
      } else if (paragraphObj.styleId === 'Heading3' || paragraphObj.styleName === 'heading 3') {
        docHtmlStr += `<h3 style="${alignmentStr}">${paragraphStr}</h3>`;
      } else if (paragraphObj.styleId === 'Heading4' || paragraphObj.styleName === 'heading 4') {
        docHtmlStr += `<h4 style="${alignmentStr}">${paragraphStr}</h4>`;
      } else if (paragraphObj.styleId === 'Heading5' || paragraphObj.styleName === 'heading 5') {
        docHtmlStr += `<h5 style="${alignmentStr}">${paragraphStr}</h5>`;
      } else if (paragraphObj.styleId === 'Heading6' || paragraphObj.styleName === 'heading 6') {
        docHtmlStr += `<h6 style="${alignmentStr}">${paragraphStr}</h6>`;
      } else {
        docHtmlStr += `<p style="${alignmentStr}">${paragraphStr}</p>`;
      }
    } else if (paragraphObj.type === 'table') {
      // 表格内容处理
      const tableObj: any = docParagraphList[i];
      docHtmlStr += tableHtmlFormat(tableObj);
    }
  }
  docContentHtml.value = `<div style="margin: 72pt;">${docHtmlStr}</div>`;
}

// 段落内容格式化
function paragraphHtmlFormat(paragraphObj: any) {
  let contentStr: string = '';

  // console.log("paragraphObj: ", paragraphObj);

  if (!paragraphObj.children) {
    return '<span></span>';
  }

  if (paragraphObj.children.length === 0) {
    return '<br/>';
  }

  /**
   * textAlign: "left"
   * textBold: false
   * textFamily: "默认字号"
   * textFont: "默认字体"
   * textIndent: false
   */

  for (let i: number = 0; i < paragraphObj.children.length; i++) {
    if (paragraphObj.children[i].type === 'text') {
      let textStr: string = paragraphObj.children[i].value;
      // 如果有html字符串，将其解析为html字符串，就可以正常展示
      textStr = escapeHTMLManually(textStr);

      let styleStr: string = `line-height: 150%;`;
      if (paragraphObj.font) {
        styleStr += `font-family: ${paragraphObj.font};`;
      }
      if (paragraphObj.fontSize) {
        styleStr += `font-size: ${paragraphObj.fontSize}pt;`;
      }
      if (props.formatObj.textFont === '默认字号') {
        styleStr = `font-size: ${paragraphObj.fontSize}pt;`;
      } else {
        styleStr = `font-size: ${props.formatObj.textFont};`;
      }

      if (props.formatObj.textFamily === '默认字体') {
        styleStr = `font-family: ${paragraphObj.font};`;
      } else {
        styleStr = `font-family: ${props.formatObj.textFamily};`;
      }
      if (props.formatObj.textIndent) {
        styleStr += 'text-indent: 2em;';
      }
      // 是否有下划线
      if (paragraphObj.isUnderline) {
        styleStr += 'text-decoration: underline;';
      }
      // 是否有删除线
      if (paragraphObj.isStrikethrough) {
        styleStr += 'text-decoration: line-through;';
      }
      // if (paragraphObj.verticalAlignment) {
      //   styleStr += `display: block; align-items: ${paragraphObj.verticalAlignment};`;
      // }
      /** font: "fzxbsjw-gb1-0" fontSize: 32 */
      // 文档标题设置固定的色值：#E03E2D
      if (paragraphObj.fontSize === 32 && paragraphObj.font === 'fzxbsjw-gb1-0') {
        styleStr += 'color: #E03E2D;';
      }
      // 是否加粗(使用 strong 标签加粗内容)
      if (props.formatObj.textBold) {
        contentStr += `<strong style="${styleStr}">${textStr}</strong>`;
      } else {
        contentStr += `<span style="${styleStr}">${textStr}</span>`;
      }
    } else if (paragraphObj.children[i].type === 'break') {
      // 换行
      contentStr += '<br/>';
    } else if (paragraphObj.children[i].type === 'image') {
      // 图片
      contentStr += IMAGE_TAG;
    } else {
      contentStr = String(contentStr);
    }
  }

  return contentStr;
}

// 表格内容格式化
function tableHtmlFormat(tableObj: any) {
  let tableStr: string = '';
  for (let i: number = 0; i < tableObj.children.length; i++) {
    // 遍历 tableRow
    const rowObj: any = tableObj.children[i];
    if (rowObj.isHeader) {
      tableStr += '<thead><tr>';
    } else {
      tableStr += '<tbody><tr>';
    }
    for (let j: number = 0; j < rowObj.children.length; j++) {
      // 遍历 tableCell
      const cellObj: any = rowObj.children[j];
      if (rowObj.isHeader) {
        tableStr += `<th>`;
      } else {
        tableStr += `<td>`;
      }
      for (let k: number = 0; k < cellObj.children.length; k++) {
        const contentObj: any = cellObj.children[k];

        let paragraphStr: string = '';
        let alignmentStr: string = '';
        if (contentObj.alignment) {
          alignmentStr = `text-align: ${contentObj.alignment};`;
        } else {
          alignmentStr = 'text-align: left;';
        }
        for (let l: number = 0; l < contentObj.children.length; l++) {
          if (contentObj.children.length > 1 && l === 0 && contentObj.indent && contentObj.indent.firstLine) {
            alignmentStr += 'text-indent: 2em;';
          }
          paragraphStr += paragraphHtmlFormat(contentObj.children[l]);
        }
        tableStr += `<p style="${alignmentStr}">${paragraphStr}</p>`;
      }
      if (rowObj.isHeader) {
        tableStr += '</th>';
      } else {
        tableStr += '</td>';
      }
    }
    if (rowObj.isHeader) {
      tableStr += '</tr></thead>';
    } else {
      tableStr += '</tr></tbody>';
    }
  }
  return `<table style="width: 100%; border-collapse: collapse;">${tableStr}</table>`;
}

const emit = defineEmits(['update:show']);

const modalShowValue = computed({
  get() {
    return props.show;
  },
  set(value: boolean) {
    emit('update:show', value);
  }
});

const catalogList = ref<any[]>([]);

// 查询目录树
async function getLogCatalogData() {
  fileList.value = [];
  // 插入文本
  ueditor.value.setContent('');
  // 设置内容光标到内容最前面
  ueditor.value.focus();

  showLoading.value = true;
  const { data, error } = await getLogCatalogAction(props.taskId!);
  showLoading.value = false;
  if (!error) {
    catalogList.value = data || [];
    analysisAllCatalog(catalogList.value);

    console.log('fileList: ', fileList.value, props.formatObj);

    showLoading.value = true;
    for (let i: number = 0; i < fileList.value.length; i++) {
      const fileObj: any = fileList.value[i];
      const { data, error } = await getHtmlByDocument(fileObj, fileObj.filePath);
      console.log('data: ', data);
      if (i === fileList.value.length - 1) {
        showLoading.value = false;
      }
    }
  }
}

/**
 * 设置的样式
 *
 * bottomSpace: 2.54
 * fifthType: "一"
 * firstType: "一"
 * fourthType: "一"
 * leftSpace: 3.18
 * rightSpace: 3.18
 * secondAlign: "center"
 * secondBold: false
 * secondFamily:"默认字号"
 * secondFont: "默认字体"
 * secondType: "一"
 * sixthType: "一"
 * textAlign: "left"
 * textBold: false
 * textFamily: "默认字号"
 * textFont: "默认字体"
 * textIndent: false
 * thirdAlign: "center"
 * thirdBold: false
 * thirdFamily: "默认字号"
 * thirdFont: "默认字体"
 * thirdType : "一" topSpace: 2.54
 */

// 递归解析所有word文档及设置标题样式
function analysisAllCatalog(catalogs: any[]) {
  for (const item of catalogs) {
    let titleStr: string = '';
    // 1、设置标题内容、序号及其样式
    // 一级目录
    if (item.type === 1) {
      firstNum.value += 1;

      secondNum.value = 0;
      thirdNum.value = 0;
      fourthNum.value = 0;
      fifthNum.value = 0;
      sixthNum.value = 0;

      /** firstAlign: "left" firstBold: false firstFamily: "默认字号" firstFont: "默认字体" */

      let firstSerial: string = '';
      if (props.formatObj.titleFormat === 1) {
        firstSerial = `${numberToChinese(firstNum.value)}、`;
      }

      let firstStyle: string = '';
      if (props.formatObj.firstBold) {
        firstStyle += 'font-weight: bold;';
      }
      if (props.formatObj.firstFamily && props.formatObj.firstFamily !== '默认字体') {
        firstStyle += `font-family: ${props.formatObj.firstFamily};`;
      }
      if (props.formatObj.firstFont && props.formatObj.firstFont !== '默认字号') {
        firstStyle += `font-size: ${props.formatObj.firstFont};`;
      }
      if (props.formatObj.firstAlign) {
        firstStyle += `text-align: ${props.formatObj.firstAlign};`;
      }

      titleStr = `<h1 style="${firstStyle}">${firstSerial}${item.title}</h1>`;
      // // 插入文本
      // ueditor.value.setContent(firstTitle, true);
      // // 设置内容光标到内容最前面
      // ueditor.value.focus();
    }

    // 二级目录
    if (item.type === 2) {
      secondNum.value += 1;

      thirdNum.value = 0;
      fourthNum.value = 0;
      fifthNum.value = 0;
      sixthNum.value = 0;

      let secondSerial: string = '';
      if (props.formatObj.titleFormat === 1) {
        secondSerial = `（${numberToChinese(secondNum.value)}）`;
      }

      let secondStyle: string = '';
      if (props.formatObj.secondBold) {
        secondStyle += 'font-weight: bold;';
      }
      if (props.formatObj.secondFamily && props.formatObj.secondFamily !== '默认字体') {
        secondStyle += `font-family: ${props.formatObj.secondFamily};`;
      }
      if (props.formatObj.secondFont && props.formatObj.secondFont !== '默认字号') {
        secondStyle += `font-size: ${props.formatObj.secondFont};`;
      }
      if (props.formatObj.secondAlign) {
        secondStyle += `text-align: ${props.formatObj.secondAlign};`;
      }

      titleStr = `<h2 style="${secondStyle}">${secondSerial}${item.title}</h2>`;
      // 插入文本
      // ueditor.value.setContent(secondTitle, true);
      // // 设置内容光标到内容最前面
      // ueditor.value.focus();
    }

    // 三级目录
    if (item.type === 3) {
      thirdNum.value += 1;

      fourthNum.value = 0;
      fifthNum.value = 0;
      sixthNum.value = 0;

      let thirdSerial: any = '';
      if (props.formatObj.titleFormat === 1) {
        thirdSerial = `${thirdNum.value}、`;
      }

      let thirdStyle: string = '';
      if (props.formatObj.thirdBold) {
        thirdStyle += 'font-weight: bold;';
      }
      if (props.formatObj.thirdFamily && props.formatObj.thirdFamily !== '默认字体') {
        thirdStyle += `font-family: ${props.formatObj.thirdFamily};`;
      }
      if (props.formatObj.thirdFont && props.formatObj.thirdFont !== '默认字号') {
        thirdStyle += `font-size: ${props.formatObj.thirdFont};`;
      }
      if (props.formatObj.thirdAlign) {
        thirdStyle += `text-align: ${props.formatObj.thirdAlign};`;
      }

      titleStr = `<h3 style="${thirdStyle}">${thirdSerial}${item.title}</h3>`;
      // 插入文本
      // ueditor.value.setContent(thirdTitle, true);
      // // 设置内容光标到内容最前面
      // ueditor.value.focus();
    }

    // 四级目录
    if (item.type === 4) {
      fourthNum.value += 1;

      fifthNum.value = 0;
      sixthNum.value = 0;

      let fourthSerial: any = '';
      if (props.formatObj.titleFormat === 1) {
        fourthSerial = `（${fourthNum.value}）`;
      }

      titleStr = `<h4 style="">${fourthSerial}${item.title}</h4>`;
      // 插入文本
      // ueditor.value.setContent(fourthTitle, true);
      // // 设置内容光标到内容最前面
      // ueditor.value.focus();
    }

    // 五级目录
    if (item.type === 5) {
      fifthNum.value += 1;

      sixthNum.value = 0;

      let fifthSerial: any = '';
      if (props.formatObj.titleFormat === 1) {
        fifthSerial = `${fifthNum.value}）`;
      }

      titleStr = `<h5 style="">${fifthSerial}${item.title}</h5>`;
      // 插入文本
      // ueditor.value.setContent(fifthTitle, true);
      // // 设置内容光标到内容最前面
      // ueditor.value.focus();
    }

    // 六级目录
    if (item.type === 6) {
      sixthNum.value += 1;

      let sixthSerial: string = '';
      if (props.formatObj.titleFormat === 1) {
        sixthSerial = `${numberToLetter(sixthNum.value)}、`;
      }

      titleStr = `<h6 style="">${sixthSerial}${item.title}</h6>`;

      // 插入文本
      // ueditor.value.setContent(sixthTitle, true);
      // // 设置内容光标到内容最前面
      // ueditor.value.focus();
    }

    // 2、解析章节正文内容、设置其样式
    // if (item.filePath) {
    //   getHtmlByDocument(item, item.filePath);
    // }

    const fileObj: any = {
      title: titleStr,
      filePath: item.filePath
    };

    fileList.value.push(fileObj);

    if (item.children && item.children.length > 0) {
      analysisAllCatalog(item.children);
    }
  }
}

// 数字转中文数字
function numberToChinese(n: number, type = 'zh') {
  let zhArr;
  let zhUnit;
  // 增加一个繁简判断
  if ((type = 'zh')) {
    zhArr = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    zhUnit = ['', '十', '百', '千', '万', '亿', '万亿', '亿亿'];
  } else if ((type = 'zhtw')) {
    zhArr = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    zhUnit = ['', '拾', '佰', '仟', '万', '亿', '万亿', '亿亿'];
  }
  // result是输出结果，unitPos是循环中当前排到的位置，wan、yi、wanyi都是单位是否添加的标志
  let result = '';
  let unitPos = 0;
  let wan = false;
  let wanyi = false;
  let yi = false;

  // console.log("zhArr[y] + result: ", result);

  while (n > 0) {
    // %为取模，n除以10最后的余数，此法为获取n的最后一位，因为后面会对n进行n=Math.floor(n/10)的位数缩减
    // 所以此法循环可有效获取n的每一位数值
    const y = n % 10;
    if (y === 0) {
      // 阿拉伯数字12356789转对应中文
      // 如果是零的话，就不会涉及到单位
      result = zhArr[y] + result;
    } else {
      // 阿拉伯数字12356789转对应中文
      // 非零的话，会涉及到单位
      // 0-4位需取十百千，5-8位只需取一次单位万，9-12位只需取一次单位亿
      if (unitPos >= 0 && unitPos < 4) {
        result = zhArr[y] + zhUnit[unitPos] + result;
      } else if (unitPos >= 4 && unitPos < 8) {
        if (!wan) {
          wan = true;
          result = zhArr[y] + zhUnit[unitPos - 4] + zhUnit[4] + result;
        } else {
          result = zhArr[y] + zhUnit[unitPos - 4] + result;
        }
      } else if (unitPos >= 8 && unitPos < 12) {
        if (!yi) {
          yi = true;
          result = zhArr[y] + zhUnit[unitPos - 8] + zhUnit[5] + result;
        } else {
          result = zhArr[y] + zhUnit[unitPos - 8] + result;
        }
      } else if (unitPos >= 12 && unitPos < 16) {
        if (!wanyi) {
          wanyi = true;
          result = zhArr[y] + zhUnit[unitPos - 12] + zhUnit[6] + result;
        } else {
          result = zhArr[y] + zhUnit[unitPos - 12] + result;
        }
      }
    }
    unitPos += 1;
    n = Math.floor(n / 10);
  }
  // 处理多个零的情况，变成一个零
  result = result.replace(/\零{2,}/g, '零');
  // 处理最后一位为零的情况
  if (result.endsWith('零')) {
    result = result.substr(0, result.length - 1);
  }
  return result;
}

// 数字转字母
function numberToLetter(num: number) {
  return String.fromCharCode(96 + num);
}

// 取消
function closeModal() {
  isBack.value = true;
  // ueditor.value.destroy();
  // ueditor.value = null;
  modalShowValue.value = false;
}

// 确认
async function downloadClick() {
  // let htmlContentStr: string = ueditor.value.getContent();
  // // console.log("htmlContentStr: ", htmlContentStr);
  //
  // // htmlContentStr = htmlContentStr.replace(/<img /g, '<img width="650" height="650"');
  // const allImages: any = getAllImagesInEditor();
  // // console.log('allImages: ', allImages);
  // if (allImages.length > 0) {
  //   // 正确的做法 - 如果不需要并行处理
  //   const promises = allImages.map(async imageTag => {
  //     // const imageSrc = 'https://img2.baidu.com/it/u=2747638305,3937495153&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=639';
  //     const result = await convertImageToBase64(imageTag.src);
  //     if (result) {
  //       // console.log('result:', result);
  //       // imageTag.src = result;
  //       htmlContentStr = htmlContentStr.replace(
  //         `<img src="${imageTag.src}" alt="${imageTag.alt}"/>`,
  //         `<img src="${result}" alt="${imageTag.alt}" width="${imageTag.clientWidth}" height="${imageTag.clientHeight}"/>`
  //       );
  //     }
  //   });
  //   await Promise.all(promises);
  // }
  // 设置表格边框
  // const htmlContent = htmlContentStr.replaceAll(/<table/g, `<table border-collapse="collapse" border="1" `);

  const htmlContent: string = await ueditorContentHandle();

  const formatContent = `
    	 	<!DOCTYPE html>
    	 	<html lang="en">
          <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>${props.title}</title>
          </head>
          <body>
             ${htmlContent}
          </body>
        </html>`;

  // const saveParams: any = {
  //   contentList: sliceStringByLength(`<div>${htmlContent}</div>`, 40000)
  // };

  console.log('内容：', formatContent);

  // const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
  // const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);
  //
  // const { data, error } = await htmlToDocAction(saveParams);
  // if (!error) {
  //   saveAs(otherUrl.fileUrl + data, `${fileName.value}.docx`, { encoding: 'UTF-8' });
  //   successMessage('文档下载成功');
  // }

  const convertedFile = htmlDocx.asBlob(formatContent);

  // 生成链接并且下载
  convertedFile.then(fileData => {
    saveAs(fileData as Blob, `${props.title}.docx`, { encoding: 'UTF-8' });
    successMessage('文档下载成功');
  });
  closeModal();
}

// 编辑器内容处理
async function ueditorContentHandle() {
  let htmlContentStr: string = ueditor.value.getContent();

  const imgSrcReg = /<img[^>]+src=[\\'|\\"]?([^(?"|?'|?>)]+)[\\'|\\"]?[^>]*>/gim;
  const imgSrcList = htmlContentStr.match(imgSrcReg);

  const maxWidth: number = 590;
  const maxHeight: number = 840;

  for (let i: number = 0; i < imgSrcList?.length; i++) {
    const imgString: string = imgSrcList[i];

    const imgSrc: string = imgString.match(/src="(.+?)"/)[1];

    const info = await getImageInfoFromBase64(imgSrc);
    if (info) {
      // console.log('info: ', info);
      if (info.width > maxWidth || info.height > maxHeight) {

        // A4纸在边距为25mm的情况下，可用区域为453px * 692px
        let newWidth: number = maxWidth;
        let newHeight: number = maxHeight;

        // 原图片宽高比例 大于 指定的宽高比例，这就说明了原图片的宽度必然 > 高度
        if (info.width / info.height >= maxWidth / maxHeight) {
          if (info.width > maxWidth) {
            newWidth = maxWidth;
            // 按原图片的比例进行缩放
            newHeight = (info.height * maxWidth) / info.width;
          } else {
            // 按原图片的大小进行缩放
            newWidth = info.width;
            newHeight = info.height;
          }
        } else {
          // 原图片的高度必然 > 宽度
          if (info.height > maxHeight) {
            newHeight = maxHeight;
            // 按原图片的比例进行缩放
            newWidth = (info.width * maxHeight) / info.height;
          } else {
            // 按原图片的大小进行缩放
            newWidth = info.width;
            newHeight = info.height;
          }
        }

        htmlContentStr = htmlContentStr.replace(
          imgString,
          `<img src='${imgSrc}' width='${newWidth}' height='${newHeight}' alt=''/>`
        );
      } else {
        htmlContentStr = htmlContentStr.replace(
          imgString,
          `<img src='${imgSrc}' width='${info.width}' height='${info.height}' alt=''/>`
        );
      }
    }
  }

  // 设置表格边框
  return htmlContentStr.replaceAll(/<table/g, `<table border-collapse="collapse" border="1" `);
}

// 获取编辑器中的所有图片
function getAllImagesInEditor() {
  const allImages = [];
  const imgTags = ueditor.value.document.getElementsByTagName('img');

  for (let i: number = 0; i < imgTags.length; i++) {
    const img = imgTags[i];
    if (img.src.includes('http://') || img.src.includes('https://')) {
      allImages.push(img);
    }
  }

  return allImages;
}
</script>

<template>
  <NModal
    v-model:show="modalShowValue"
    preset="card"
    :title="title"
    class="h-785px w-90vw"
    :mask-closable="false"
    @close="closeModal"
  >
    <NSpin :show="showLoading" :description="loadingDes" :rotate="false" size="large">
      <template #icon>
        <img src="@/assets/imgs/spin-loading.gif" alt="" width="240" height="240" />
      </template>
      <div class="flex-col">
        <div class="flex">
          <div class="catalog">
            <div id="catalog_wrapper">
              <div class="catalog_title_box">
                <span class="catalog_title">章节名称</span>
              </div>
              <NScrollbar content-class="catalog-list" class="max-h-581px">
                <div id="catalog_box" class="catalog-list"></div>
              </NScrollbar>
            </div>
          </div>
          <div v-if="isBack" class="content-box bg-white"></div>
          <div v-else class="content-box">
            <VueUeditorWrap
              v-model="contentHtml"
              editor-id="download_editor"
              :config="editorConfig"
              :editor-dependencies="editorDependencies"
              @ready="readyHandle"
            />
          </div>
        </div>
      </div>
    </NSpin>
    <template #footer>
      <NSpace class="w-full" :size="24" justify="end">
        <NButton class="w-72px" @click="closeModal">取消</NButton>
        <NButton class="w-72px" type="primary" :disabled="showLoading" @click="downloadClick">下载</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style>
#catalog_box li {
  color: #333;
  margin: 10px 0 0;
  cursor: pointer;
  word-break: break-all;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
#catalog_box li[type='H1'] {
  font-size: 16px;
  font-weight: bold;
}
#catalog_box li[type='H2'] {
  font-weight: bold;
}
#catalog_box li[type='H2'] span {
  font-size: 14px;
  padding-left: 10px;
}
#catalog_box li[type='H3'] span {
  font-size: 12px;
  padding-left: 20px;
}
#catalog_box li[type='H4'] {
  font-size: 10px;
  padding-left: 30px;
}
#catalog_box li[type='H5'] {
  font-size: 10px;
  padding-left: 40px;
}
#catalog_box li[type='H6'] {
  font-size: 10px;
  padding-left: 50px;
}
.sectionItem {
  height: 20px;
  padding: 4px;
  cursor: pointer;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.sectionItem span {
  display: inline-block;
}
.itemTitle {
  max-width: 280px;
  word-break: break-all;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>

<style scoped lang="scss">
$catalogWidth: 310px;

#catalog_box ul {
  margin: 0px;
  padding: 0px 0px 0px 20px;
}
.catalog {
  width: $catalogWidth;
  height: 643px;
  background: white;
  border-radius: 2px;
  z-index: 900;
  border-left: 1px solid #e5e7eb;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
}
#catalog_wrapper {
  padding: 15px 0 15px 0px;
  width: 100%;
}
.content-box {
  width: calc(100% - $catalogWidth);
}
.catalog_title_box {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  padding-bottom: 3px;
  border-bottom: 1px dashed #ccc;
  background: #ffffff;
  position: sticky;
  top: 0;
  z-index: 500;
  .catalog_title {
    font-weight: bold;
    font-size: 18px;
    margin-left: 20px;
    line-height: 25px;
  }
}
#download_editor {
  width: 100%;
  border: 1px solid #cccccc;
}
:deep(.edui-editor) {
  width: auto !important;
}
:deep(.edui-editor-iframeholder) {
  width: auto !important;
}
:deep(.n-spin) {
  width: auto;
  height: auto;
}
.catalog-list {
  list-style: none;
}
</style>
